<template>
  <!-- 收益趋势折柱图 -->
  <div class="w-full echart-box">
    <a-skeleton-shape v-if="loading" class="w-full" style="height: 364px" />
    <template v-else>
      <a-empty
        style="background-color: rgba(248, 250, 252, 1)"
        description="根据您的筛选统计数据时发现暂无数据，请重新筛选"
        v-if="echartDataEmpty"
      />
      <div v-else class="echart-item" ref="echartBoxRef"></div>
    </template>
  </div>
</template>
<script setup lang="ts">
  import useEcharts from '@/hooks/useEcharts'
  import TooltipTable from './TooltipTable.vue'

  import { ref, nextTick, render, createVNode, watch, onMounted, onBeforeUnmount } from 'vue'
  import dayjs from 'dayjs'
  import { dispose } from 'echarts/core'

  const props = defineProps({
    echartData: {
      type: Array,
      default: () => [],
    },
  })

  const loading = ref(true)
  const echartBoxRef = ref()
  let echart_axis: string[] = []
  let echart_series: any[] = []

  let echartInstance: any = null
  const echartInt = () => {
    const option: any = {
      grid: {
        top: '8%',
        left: 43,
        right: '2%',
        bottom: '15%',
        containLabel: true,
      },
      tooltip: {
        trigger: 'axis',
        appendToBody: true,
        appendTo: 'body',
        enterable: true, // 鼠标是否可进入提示框浮层中
        confine: true,
        formatter: (params: any) => {
          // 挂载 maptooltip 组件
          const com = createVNode(TooltipTable, {
            dataSource: params[0]?.data,
          })
          let mountNode = document.createElement('div')
          render(com, mountNode)
          return com.el
        },
        // 修改 echarts 默认 tooltips 样式
        extraCssText: 'padding: 0px; border-radius: 6px; border: none',
      },
      legend: {
        data: ['收入', '支出', '总收益'],
        top: 'bottom',
        padding: [5, 5, 25, 5],
        textStyle: {
          fontSize: 16,
        },
      },
      xAxis: {
        type: 'category',
        data: echart_axis,
        axisLine: {
          show: true,
          lineStyle: {
            color: '#eee',
          },
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          color: '#666',
          margin: 20,
        },
        axisPointer: {
          show: true,
          lineStyle: {
            color: '#4080FF',
            width: 2,
          },
        },
      },
      yAxis: {
        type: 'value',
        name: '单位: 元',
        minInterval: 1,
        nameTextStyle: {
          color: '#666',
          align: 'right',
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#eee',
          },
        },
        axisLabel: {
          color: '#666',
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: [5, 10],
            dashOffset: 5,
          },
        },
      },
      dataZoom: [
        {
          type: 'slider',
          realtime: true,
          height: 14, //组件高度
          moveHandleSize: 15,
          left: '4%', //左边的距离
          right: '4%', //右边的距离
          bottom: '0%', //下边的距离
          xAxisIndex: [0],
          showDataShadow: false,
          show: echart_axis.length > 20 ? true : false, // 是否展示
          fillerColor: 'rgba(2,110,252,1)', // 滚动条颜色
          borderColor: 'rgba(17, 100, 210, 0.12)',
          backgroundColor: 'rgba(232,244,255,0.51)', //两边未选中的滑动条区域的颜色
          handleSize: 0, //两边手柄尺寸
          showDetail: false, //拖拽时是否展示滚动条两侧的文字
          startValue: 0, // 从头开始。
          endValue: 20,
        },
        {
          type: 'inside', // 支持内部鼠标滚动平移
          startValue: 0, // 从头开始。
          endValue: 20,
          zoomLock: true, // 是否只平移不缩放
          zoomOnMouseWheel: false, // 关闭滚轮缩放
          moveOnMouseWheel: false, // 关闭滚轮平移
          moveOnMouseMove: false, // 关闭鼠标拖动平移
          preventDefaultMouseMove: false, // 鼠标移动能触发数据窗口平移
        },
      ],
      series: echart_series,
    }

    nextTick(() => {
      echartInstance = useEcharts(echartBoxRef.value)
      echartInstance?.setOption(option, {
        notMerge: true,
      })
    })
    loading.value = false
  }

  const echart_bar_option = {
    type: 'bar',
    stack: 'total',
  }
  const echart_line_option = {
    type: 'line',
    showSymbol: false,
  }

  const income_data = ref<any>({
    ...echart_bar_option,
    name: '收入',
    data: [],
    itemStyle: {
      color: '#1890FF',
      borderRadius: 2,
    },
  })
  const expense_data = ref<any>({
    ...echart_bar_option,
    name: '支出',
    data: [],
    itemStyle: {
      color: '#86DF6C',
      borderRadius: 2,
    },
  })
  const line_data = ref<any>({
    ...echart_line_option,
    data: [],
    name: '总收益',
    itemStyle: {
      color: '#EC6571',
    },
  })

  onMounted(() => {
    window.addEventListener('resize', () => {
      echartInstance?.resize()
    })
  })

  onBeforeUnmount(() => {
    if (echartInstance) {
      dispose(echartInstance)
    }
  })

  const echartDataEmpty = ref(true)
  watch(
    () => props.echartData,
    (newVal: any) => {
      echart_axis = []
      income_data.value.data = []
      expense_data.value.data = []
      line_data.value.data = []
      echart_series = []
      loading.value = true

      const hasData = newVal?.some((item: any) => {
        const hasBarData = item.barDataList?.some((barItem: any) => barItem.totalRevenueAmount != 0 || barItem.totalExpenditureAmount != 0)
        const hasLineData = item.lineDataList?.some((lineItem: any) => lineItem.totalProfitAmount != 0)
        return hasBarData || hasLineData
      })

      if (!hasData) {
        loading.value = false
        echartDataEmpty.value = true
        return
      } else {
        echartDataEmpty.value = false
      }

      if (newVal.length > 0) {
        newVal.forEach((item: any) => {
          // 横坐标
          echart_axis.push(dayjs(item.date).format('MM-DD'))

          // 柱状图数据
          item.barDataList.forEach((barItem: any) => {
            income_data.value.data.push({
              date: item.date,
              value: barItem.totalRevenueAmount,
              infoList: item.infoList,
              totalRevenueAmount: item.totalRevenueAmount,
              totalExpenditureAmount: item.totalExpenditureAmount,
              totalProfitAmount: item.totalProfitAmount,
              label: {
                show: barItem.totalRevenueAmount == 0 ? false : true,
                position: 'top',
              },
            })
          })

          item.barDataList.forEach((barItem: any) => {
            expense_data.value.data.push({
              date: item.date,
              value: -barItem.totalExpenditureAmount,
              infoList: item.infoList,
              totalRevenueAmount: item.totalRevenueAmount,
              totalExpenditureAmount: item.totalExpenditureAmount,
              totalProfitAmount: item.totalProfitAmount,
              label: {
                show: barItem.totalExpenditureAmount == 0 ? false : true,
                position: 'bottom',
              },
            })
          })

          // 折线图数据
          item.lineDataList.forEach((lineItem: any) => {
            line_data.value.data.push({
              date: item.date,
              value: lineItem.totalProfitAmount,
              infoList: item.infoList,
              totalRevenueAmount: item.totalRevenueAmount,
              totalExpenditureAmount: item.totalExpenditureAmount,
              totalProfitAmount: item.totalProfitAmount,
            })
          })
        })

        echart_series = [income_data.value, expense_data.value, line_data.value]
        echartInt()
      }
    },
    {
      immediate: true,
      deep: true,
    }
  )
</script>
<style lang="less" scoped>
  .echart-box {
    width: 100%;

    .echart-item {
      height: 364px;
    }
  }
</style>
